package com.securitydome05.service;

import com.securitydome05.dao.UserDao;
import com.securitydome05.pojo.Role;
import com.securitydome05.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {

    //dao
    private  final UserDao userDao;
    @Autowired
    public MyUserDetailsService(UserDao userDao) {
        this.userDao = userDao;
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //返回用户
        User user = userDao.loadUserByUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new UsernameNotFoundException("用户名为空");
        }
        //查询他的权限信息
        List<Role> roleByUid = userDao.getRoleByUid(user.getId());
        user.setRoles(roleByUid);
        return user;
    }
}
